package com.gitee.huxing.framework.core;

import com.alibaba.fastjson.JSON;
import com.gitee.huxing.framework.core.filter.Filter;
import com.gitee.huxing.framework.core.module.RequestInfo;
import com.gitee.huxing.framework.core.module.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.framework.core
 * @ClassName: ServiceInterceptorHandler
 * @Author: huxing
 * @DateTime: 2021-10-03 下午11:36
 */
@Slf4j
public class ServiceInterceptorHandler<T> extends AbstractInvokeHandler implements MethodInterceptor  {

    public ServiceInterceptorHandler(Class<T> serviceClass, String url, Filter[] filters) {
        super(serviceClass, url, filters);
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] params, MethodProxy methodProxy) throws Throwable {
        // 初始化业务请求对象
        RequestInfo request = new RequestInfo();
        request.setServiceClass(this.serviceClass.getName());
        request.setMethod(method.getName());
        request.setParams(params);

        // 过滤处理
        if (null!=filters){
            for (Filter filter:filters){
                if (!filter.filter(request)){
                    return null;
                }
            }
        }

        // 调用接口处理请求对象 - 增加错误捕捉，返回错误提示
        ResponseInfo response = new ResponseInfo();
        try {
            response = this.post(request, url);
        } catch (Exception ex){
            response.setStatus(false);
            response.setException(ex);
        }
        // 返回结果提示
        return JSON.parse(response.getResult().toString());
    }
}
